package com.kizuki.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NoBlockClient {

    private SocketChannel channel;

    private void initClient(String host, int port) throws IOException {
        InetSocketAddress serbAddr = new InetSocketAddress(host, port);
        this.channel = SocketChannel.open(serbAddr);
    }

    private void sendAndRecv(String words) throws IOException {
        byte[] msg = words.getBytes();
        ByteBuffer clientBuffer = ByteBuffer.wrap(msg);
        ByteBuffer serverBuffer = ByteBuffer.allocate(20);

        System.out.println("Client sending: " + words);
        channel.write(clientBuffer);

        channel.read(serverBuffer);
        System.out.println("Client received: " + new String(serverBuffer.array()));

        channel.close();
    }

    public static void main(String[] args) {
        int num = 4;
        for (int i = 0; i < num; i++) {
            final int temp = i;
            new Thread(()->{
                try {
                    NoBlockClient client = new NoBlockClient();
                    client.initClient("localhost", NoBlockServer.PORT);
                    client.sendAndRecv("I am a client" + temp);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("Io 异常");
                } finally {
                    System.out.println("client" + temp + " 退出");
                }
            }).start();
        }
    }

}


